// src/main/java/com/bookmanager/controller/BorrowController.java
package com.bookmanager.controller;

import com.bookmanager.model.User;
import com.bookmanager.service.BorrowService;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/borrow")
public class BorrowController extends HttpServlet {
    private BorrowService borrowService = new BorrowService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");

        if (user == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        if ("borrow".equals(action)) {
            borrowBook(request, response, user);
        } else if ("return".equals(action)) {
            returnBook(request, response, user);
        }
    }

    private void borrowBook(HttpServletRequest request, HttpServletResponse response, User user) throws IOException {
        try {
            int bookId = Integer.parseInt(request.getParameter("bookId"));

            boolean success = borrowService.borrowBook(user.getUserId(), bookId);

            if (success) {
                response.sendRedirect("books?message=borrow_success");
            } else {
                response.sendRedirect("books?message=borrow_failed");
            }
        } catch (NumberFormatException e) {
            response.sendRedirect("books?message=invalid_book_id");
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect("books?message=system_error");
        }
    }

    private void returnBook(HttpServletRequest request, HttpServletResponse response, User user) throws IOException {
        try {
            int bookId = Integer.parseInt(request.getParameter("bookId"));

            boolean success = borrowService.returnBook(user.getUserId(), bookId);

            if (success) {
                response.sendRedirect("books?message=return_success");
            } else {
                response.sendRedirect("books?message=return_failed");
            }
        } catch (NumberFormatException e) {
            response.sendRedirect("books?message=invalid_book_id");
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect("books?message=system_error");
        }
    }
}
